<?php

namespace app\health\model;

use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;


class HealthCoupon extends Model
{
    // 表名
    protected $name = 'health_coupon';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    protected $append = [
        'condition_type_text',
        'get_type_text',
        'use_time_text',
        'send_total_text'
    ];

    /**
     * 发放总量
     * @time 2023年06月07日
     * @return string
     */
    public function getSendTotalTextAttr($val, $data)
    {
        return $data['send_total_type'] == 1
            ? '不限量'
            : $data['send_total'];
    }


    public function getStatusList()
    {
        return ['  1' => __('Status   1'), '  2' => __('Status   2'), ' 3' => __('Status  3')];
    }

    /**
     * 使用门槛
     * @param [type] $value
     * @param [type] $data
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function getConditionTypeTextAttr($value, $data)
    {
        if ($data['condition_type'] == 1) {
            return '无门槛, ' . '减' . $data['money'] . '元';
        }
        return '订单满' . $data['condition_money'] . '元, ' . '减' . $data['money'] . '元';
    }

    /**
     * 获取用券时间
     * @time 2023年06月07日
     * @return string
     */
    public function getUseTimeTextAttr($val, $data)
    {
        $useTimeText = '';
        switch ($data['use_time_type']) {
            case 1:
                $start       = date('Y-m-d H:i:s', $data['use_time_start']);
                $end         = date('Y-m-d H:i:s', $data['use_time_end']);
                $useTimeText = $start . ' ~ ' . $end;
                break;
            case 2:
                $useTimeText = '领取当日起' . $data['use_time'] . '天内可用';
                break;
            case 3:
                $useTimeText = '领取次日起' . $data['use_time'] . '天内可用';
                break;
        }
        return $useTimeText;
    }

    public function getGetTypeTextAttr($val, $data)
    {
        return $data['get_type'] == 1 ? '用户领取' : '商家发放';
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list  = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delete_time']) ? $data['delete_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setUseTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeleteTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * 用户领取优惠券
     * @param $couponID
     * @param $userId
     * @param int $channel
     * @return HealthCouponList
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @Author 张旭鹏
     * @DateTime 2023-06-16
     */
    public static function receive($couponID, $userId, int $channel = 2): HealthCouponList
    {
        $coupon = self::where('id', $couponID)->find();
        if (!$coupon) {
            throw new Exception('优惠券不存在');
        }
        if ($coupon->status == 1) {
            throw new Exception('优惠券尚未开放领取，敬请期待');
        }
        if ($coupon->status == 3) {
            throw new Exception('领取失败，优惠券活动已结束');
        }
        // 计算出券最后可用时间
        $invalid_time = self::couponInvalidTime($coupon);
        // 发放优惠券
        $data = [
            'channel'      => $channel,
            'user_id'      => $userId,
            'coupon_id'    => $coupon['id'],
            'order_id'     => 0,
            'status'       => 0,
            'use_time'     => 0,
            'invalid_time' => $invalid_time,
        ];
        return HealthCouponList::create($data);
    }

    public static function changYouExchange($couponID, $userId, $orderId): HealthCouponList
    {
        $isExist = HealthCouponList::where([
            'user_id'        => $userId,
            'coupon_id'      => $couponID,
            'third_order_id' => $orderId,
        ])->find();
        if ($isExist) {
            throw new Exception('优惠券已兑换');
        }
        $coupon = self::where('id', $couponID)->find();
        if (!$coupon) {
            throw new Exception('优惠券不存在');
        }
        if ($coupon->status == 1) {
            throw new Exception('优惠券尚未开放领取，敬请期待');
        }
        if ($coupon->status == 3) {
            throw new Exception('领取失败，优惠券活动已结束');
        }
        // 计算出券最后可用时间
        $invalid_time = self::couponInvalidTime($coupon);
        // 发放优惠券
        $data = [
            'channel'        => 3,
            'user_id'        => $userId,
            'coupon_id'      => $coupon['id'],
            'order_id'       => 0,
            'status'         => 0,
            'use_time'       => 0,
            'invalid_time'   => $invalid_time,
            'third_order_id' => $orderId,
        ];
        return HealthCouponList::create($data);
    }

    /**
     * 计算出券最后可用时间
     * @param [type] $coupon
     * @Author 张旭鹏
     * @DateTime 2023-06-16
     */
    protected static function couponInvalidTime($coupon)
    {
        $invalid_time = 0;
        switch ($coupon['use_time_type']) {
            case 1:
                $invalid_time = $coupon['use_time_end'];
                break;
            case 2:
                $invalid_time = time() + ($coupon['use_time'] * 86400);
                break;
            case 3:
                $time         = strtotime(date('Y-m-d', strtotime("+1 day")));
                $invalid_time = $time + ($coupon['use_time'] * 86400);
        }
        return $invalid_time;
    }
}
